package cn.iocoder.yudao.module.reading.convert.community;

import cn.iocoder.yudao.module.reading.controller.app.community.vo.draft.DraftCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.community.vo.draft.DraftRespVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.community.CommunityDraftDO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 社区草稿 Convert
 *
 * @author 芋道源码
 */
@Mapper
public interface CommunityDraftConvert {

    CommunityDraftConvert INSTANCE = Mappers.getMapper(CommunityDraftConvert.class);

    ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 转换为草稿DO
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "userId", ignore = true)
    @Mapping(target = "expireTime", ignore = true)
    @Mapping(target = "extraData", ignore = true)
    CommunityDraftDO convert(DraftCreateReqVO reqVO);

    /**
     * 转换为草稿响应VO
     */
    default DraftRespVO convert(CommunityDraftDO draftDO) {
        if (draftDO == null) {
            return null;
        }

        DraftRespVO respVO = new DraftRespVO();
        respVO.setId(draftDO.getId());
        respVO.setType(draftDO.getType());
        respVO.setContent(draftDO.getContent());
        respVO.setCreateTime(draftDO.getCreateTime());
        respVO.setUpdateTime(draftDO.getUpdateTime());

        // 转换JSON字段
        if (draftDO.getImages() != null) {
            try {
                respVO.setImages(OBJECT_MAPPER.readValue(draftDO.getImages(), new TypeReference<List<String>>() {}));
            } catch (Exception e) {
                // 忽略JSON解析错误
            }
        }

        return respVO;
    }

    /**
     * 将图片列表转换为JSON字符串
     */
    default String convertImagesToJson(List<String> images) {
        if (images == null || images.isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(images);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将JSON字符串转换为图片列表
     */
    default List<String> convertJsonToImages(String json) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 计算草稿过期时间（7天后过期）
     */
    default LocalDateTime calculateExpireTime() {
        return LocalDateTime.now().plusDays(7);
    }

}
